<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/2/7
 * Time: 17:25
 */

namespace app\admin\controller;


use app\admin\lib\AdminController;
use app\admin\model\ApiResponse;
use app\common\model\SpecialColumn;
use think\Db;
use think\Log;
use think\Request;

class Column extends AdminController
{
    public function index(Request $request) {
        if ($request->isGet()) {
            return $this->list();
        } elseif ($request->isDelete()) {
            return $this->shift();
        } else {
            return json([], 405);
        }
    }
    private function list() {
        $form = $this->getAndCheckForm([
            ['teacher_id', 'integer',],
        ]);
        $teacherId = $form['teacher_id']??0;
        $re = SpecialColumn::manageList($this->limit,$this->offset, intval($teacherId),
            -1,$form['keywords']??null);
        return $re;
    }
    private function shift() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
            ['on','require|integer',],
        ]);
        SpecialColumn::setStatus($form['id'],$form['on']?SpecialColumn::STATUS_ON:SpecialColumn::STATUS_OFF);
        return ApiResponse::success();
    }


    public function essay(Request $request) {
        return ApiResponse::success($request->param());
    }

    /**
     * save
     * 保存专栏数据
     *
     * @return ApiResponse
     */
    public function save()
    {
        $form = $this->getAndCheckForm();

        if (isset($form['column_id'])) { // 更新
            Db::startTrans();
            try {
                SpecialColumn::where('column_id', $form['column_id'])->update(['feed'=>$form['feed']]);

                Db::commit();
                return ApiResponse::success();
            } catch (\Exception $e) {
                Db::rollback();
                Log::error($e->getMessage());
                return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED, $e->getMessage());
            }
        } else {
            // todo 新增
        }
    }
}